<template>
  <MySplitPanes>
    <pane size="15" min-size="15" max-size="15">
      <div class="my-flex-column w100 h100">
        <DeviceFormulaNodeMenu @node-click="onDeviceFormulaNodeClick" select-first-node></DeviceFormulaNodeMenu>
      </div>
    </pane>
    <pane>
      <div class="my-flex-column w100 h100">
        <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" @submit.stop.prevent>
            <el-form-item label="配方详情">
              <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onQuery">查询</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card class="my-fill mt8" shadow="never">
          <div class="my-tools-box mb8 my-flex my-flex-between">
            <div>
              <el-button v-auth="'api:industry:formula-detail:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增
              </el-button>
              <el-button v-auth="'api:industry:formula-detail:add'" type="primary" icon="ele-CopyDocument"
                @click="onCopyAdd">
                复制
              </el-button>
              <el-button v-auth="'api:industry:formula-detail:batch-soft-delete'" type="primary" icon="ele-Delete"
                @click="onBatchDelete">
                批量删除
              </el-button>
            </div>
            <div>
              <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
                <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
                  @click="state.showQuery = !state.showQuery" />
              </el-tooltip>
            </div>
          </div>
          <el-table ref="tableRef" v-loading="state.loading" :data="state.formulaDetailListData"
            @sort-change="onSortChange" row-key="id" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" :reserve-selection="true" />
            <el-table-column prop="stationCode" label="工站代号" width="120" show-overflow-tooltip />
            <el-table-column prop="stationName" label="工站名称" width="120" show-overflow-tooltip />
            <el-table-column prop="byteOffset" label="偏移量" width="70" show-overflow-tooltip />
            <el-table-column prop="plcDataType" label="数据类型" width="100" show-overflow-tooltip align="center">
              <template #default="{ row }">
                <el-tag>{{ convertPLCDataTypeToLabel(row.plcDataType) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="paramKey" label="描述" width="120" show-overflow-tooltip align="center" />
            <el-table-column prop="paramValue" label="参数值" width="100" show-overflow-tooltip align="center" />
            <el-table-column prop="sort" label="排序" width="80" align="center" sortable="custom" show-overflow-tooltip />
            <el-table-column label="状态" width="80" align="center" fixed="right">
              <template #default="{ row }">
                <el-switch v-if="auth('api:industry:formula-detail:set-enable')" v-model="row.enabled"
                  :loading="row.loading" :active-value='true' :inactive-value='false' inline-prompt active-text="开启"
                  inactive-text="关闭" :before-change="() => onSetEnable(row)" />
                <template v-else>
                  <el-tag type="success" v-if="row.enabled">启用</el-tag>
                  <el-tag type="danger" v-else>禁用</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140" header-align="center" align="center" fixed="right">
              <template #default="{ row }">
                <el-button v-auth="'api:industry:formula-detail:update'" icon="ele-EditPen" size="small" text
                  type="primary" @click="onEdit(row)">编辑</el-button>
                <my-dropdown-more v-auths="['api:industry:formula-detail:soft-delete']">
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-if="auth('api:industry:formula-detail:soft-delete')"
                        @click="onDelete(row)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </my-dropdown-more>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 10px">
            <el-pagination v-model:currentPage="state.pageInput.currentPage"
              v-model:page-size="state.pageInput.pageSize" :total="state.total" :page-sizes="[10, 20, 50, 100]" small
              background @size-change="onSizeChange" @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </el-card>
        <FormulaDetailForm ref="formulaDetailFormRef" :title="state.formulaDetailFormTitle"></FormulaDetailForm>
        <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure"></MyFilterDialog>
        <FormulaDetailCopy ref="formulaDetailCopyFormRef" :title="state.formulaDetailCopyFormTitle"></FormulaDetailCopy>
      </div>
    </pane>
  </MySplitPanes>

</template>
<script setup lang="ts" name="industry/formula-detail">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { PageInputFormulaDetailGetPageInput, FormulaDetailGetPageInput, FormulaDetailGetPageOutput, FormulaDetailGetOutput, SortInput, DeviceFormulaGetOutput, PLCDataTypeEnum } from '/@/api/industry/data-contracts'
import { FormulaDetailApi } from '/@/api/industry/FormulaDetail'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable } from 'element-plus'
import { Pane } from 'splitpanes'
import { Loading } from '@element-plus/icons-vue/dist/types'
import { number } from 'echarts'

const DeviceFormulaNodeMenu = defineAsyncComponent(() => import('/@/views/industry/device-formula/compoents/device-formula-node-menu.vue'))
const MySplitPanes = defineAsyncComponent(() => import('/@/components/my-layout/split-panes.vue'))
const MyDropdownMore = defineAsyncComponent(() => import('/@/components/my-dropdown-more/index.vue'))
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))
const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const FormulaDetailForm = defineAsyncComponent(() => import('./compoents/formula-detail-form.vue'))
const FormulaDetailCopy = defineAsyncComponent(() => import('./compoents/formula-detail-copy-form.vue'))
const formulaDetailFormRef = ref()
const formulaDetailCopyFormRef = ref()
const { proxy } = getCurrentInstance() as any
const getSortList = (data: { prop: string; order: any }) => {
  return [
    {
      propName: data.prop,
      order: data.order === 'ascending' ? 0 : data.order === 'descending' ? 1 : undefined,
    },
  ] as [SortInput]
}
const defalutSort = { prop: 'sort', order: 'ascending' }
const state = reactive({
  loading: false,
  showQuery: true,
  formulaDetailFormTitle: '',
  formulaDetailCopyFormTitle: '',
  total: 0,
  formulaIds: [] as Array<number>,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    sortList: getSortList(defalutSort),
    filter: {
      deviceFormulaId: 0,
      deviceFormulaName: ''
    } as FormulaDetailGetPageInput,
    dynamicFilter: {
    },
  } as PageInputFormulaDetailGetPageInput,
  formulaDetailListData: [] as Array<FormulaDetailGetPageOutput>,
  filters: [
    {
      field: 'formulaDetail',
      operator: 'Contains',
      description: '产品代号',
      componentName: 'el-input',
      defaultSelect: true,
    },
    {
      field: 'productName',
      operator: 'Contains',
      description: '产品名称',
      componentName: 'el-input',
      defaultSelect: false,
    },
  ] as Array<DynamicFilterInfo>,
})

const plcDataType = {
  0: 'BOOL',
  1: 'BYTE',
  2: 'WORD',
  3: 'DWORD',
  4: 'INT',
  5: 'DINT',
  6: 'REAL',
  7: 'LREAL',
  8: 'STRING'
} as const

const convertPLCDataTypeToLabel = (dataType: PLCDataTypeEnum) => plcDataType[dataType] as string;

onMounted(() => {
  onQuery()
  eventBus.off('refreshFormulaDetail')
  eventBus.on('refreshFormulaDetail', async () => {
    onQuery()
  })
})

onBeforeMount(() => {
  eventBus.off('refreshFormulaDetail')
})
const handleSelectionChange = (rows: FormulaDetailGetPageOutput[]) => {
  state.formulaIds = rows.map(row => row.id);
}

const onSortChange = (data: { column: any; prop: string; order: any }) => {
  state.pageInput.sortList = getSortList(data)
  onQuery()
}
//查询分页
const onQuery = async () => {
  state.loading = true
  const res = await new FormulaDetailApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })

  state.formulaDetailListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}
const onFilterSure = (dynamicFilter: any) => {
  state.pageInput.dynamicFilter = dynamicFilter
  onQuery()
}
//新增
const onAdd = (row: FormulaDetailGetOutput) => {
  state.formulaDetailFormTitle = `新增配方代号【${state.pageInput.filter?.deviceFormulaName}】详情`
  formulaDetailFormRef.value.open({ deviceFormulaId: state.pageInput.filter?.deviceFormulaId })
}
const onCopyAdd = (row: any) => {
  state.formulaDetailCopyFormTitle = "复制详情至其他工站"
  formulaDetailCopyFormRef.value.open();
}
//修改
const onEdit = (row: FormulaDetailGetOutput) => {
  state.formulaDetailFormTitle = `编辑配方详情`
  formulaDetailFormRef.value.open(row)
}

//删除
const onDelete = (row: FormulaDetailGetOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除当前选中行?`)
    .then(async () => {
      await new FormulaDetailApi().softDelete({ id: row.id }, { loading: true, showSuccessMessage: true })
      onQuery()
    })
    .catch(() => { })
}

//批量删除
const onBatchDelete = () => {
  proxy.$modal
    .confirmDelete(`确认要删除选中行数据?`)
    .then(async () => {
      await new FormulaDetailApi().batchSoftDelete(state.formulaIds, { loading: true, showSuccessMessage: true })
      onQuery()
    }).catch(() => { })
}

//启用或禁用
const onSetEnable = (row: FormulaDetailGetOutput & { loading: boolean }) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要${row.enabled ? '禁用' : '启用'}当前${row.paramKey}参数?`)
      .then(async () => {
        row.loading = true
        const res = await new FormulaDetailApi()
          .setEnable({ formulaDetailId: row.id, enabled: !row.enabled }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
            row.loading = false
          })
        if (res && res.success) {
          resolve(true)
        } else {
          reject(new Error('Cancel'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}


const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}

const onDeviceFormulaNodeClick = (node: DeviceFormulaGetOutput | null) => {
  if (state.pageInput.filter) {
    state.pageInput.filter.deviceFormulaId = node?.id
    state.pageInput.filter.deviceFormulaName = node?.formulaName
  }
  onQuery()
}
</script>